package top.lixunda.demo.seata.account.rest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import top.lixunda.demo.seata.account.service.IDbAccountService;
import top.lixunda.demo.seata.common.controller.MessageObject;
import top.lixunda.demo.seata.common.entity.DbAccount;
import top.lixunda.demo.seata.common.exception.AppException;
import top.lixunda.demo.seata.feign.AccountClient;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author LiXunda
 * @version time:2019/10/25 12:53
 */
@RestController
@Slf4j
public class AccountController implements AccountClient {

    private final IDbAccountService accountService;

    @Autowired
    public AccountController(IDbAccountService accountService) {
        this.accountService = accountService;
    }

    @Override
    public MessageObject<Boolean> deduction(int accountId, double money) {
        DbAccount account = accountService
                .getOne(new QueryWrapper<DbAccount>().lambda().eq(DbAccount::getAId, accountId), false);
        if (account == null) {
            throw AppException.message("用户不存在");
        }
        System.out.println(account.toString());
        double last = account.getAMoney().doubleValue() - money;
        System.out.println("last = " + last);
        if (last < 0) {
            throw new AppException("余额不足");
        }
        log.debug("足够的余额");
        account.setAMoney(new BigDecimal(last));
        accountService.updateById(account);
        return MessageObject.success(true);
    }

    @Override
    public MessageObject<List<DbAccount>> queryAll() {
        return MessageObject.success(accountService.list());
    }

}
